package com.xzx.flink.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * 批处理的word count
 *
 * @author xinzhixuan
 * @version V1.0.0
 * @date 2021/4/9
 **/
public class BatchWordCount {
    public static void main(String[] args) throws Exception {

        //构建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        String filePath = "/Users/xinzhixuan/work/git/flink-study-java/src/main/resources/wordcount.txt";
        // readTextFile返回的是DataSource,但DataSource是DataSet的子类
        DataSet<String> inputDataSet = env.readTextFile(filePath);

        // 将行切割后平铺，然后转成二元组，
        // 注意：这里的Tuple2是flink封装的java中二元组不是scala中二元组
        // FlatMapOperator 继承自DataSet
        FlatMapOperator<String, Tuple2<String, Integer>> flatMap = inputDataSet
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    // value就是输入的行
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] line = value.split(" ");
                        for (String word : line) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                });
        // UnsortedGrouping不会继承DataSet类，但是成员变量包含DataSet
        UnsortedGrouping<Tuple2<String, Integer>> group = flatMap
                .groupBy(0);
        // AggregateOperator继承自DataSet类
        AggregateOperator<Tuple2<String, Integer>> sum = group// 用第0个元素分组
                .sum(1);//分组之后用第2个元素求和

        sum.print();
    }
}
